import os
import xmind, shutil
from collections import defaultdict
from datetime import datetime
from config import datas_dir
import logging

# 设置日志
logger = logging.getLogger(__name__)
class JsonToXmind(object):
    def __init__(self,new_root,json_data,timestamp):
        """复制模板文件，文件名：新根标题_日期时间.xmind"""
        timestamp = timestamp
        self.base_name = f"{new_root}_{timestamp}.xmind"
        self.new_file = os.path.join(datas_dir,self.base_name)
        self.model_path =os.path.join(datas_dir,'model.xmind')
        shutil.copy2(self.model_path, self.new_file)
        self.new_root=new_root
        self.json_data = json_data

    def json_to_xmind(self):
        # 复制xmind模版
        output_file =self.new_file
        # 4. 内存新建工作簿
        workbook = xmind.load(output_file)  # 文件不存在则创建空簿
        sheet = workbook.getPrimarySheet()
        root_topic = sheet.getRootTopic()
        # 1. 替换根节点标题
        root_topic.setTitle(self.new_root)
        # 2.遍历子节点
        grouped_data = defaultdict(list)
        for item in self.json_data:
            # print(str(self.json_data))
            grouped_data[item['testpoint']].append(item)
        # print(str(grouped_data))
        # 3.开始追加测试点
        for testpoint, items in grouped_data.items():
            testpoint_topic = root_topic.addSubTopic()  # 1. 先拿对象
            testpoint_topic.setTitle(testpoint)  # 2. 再写文字
            for item in items:
                # 用例标题
                title_topic = testpoint_topic.addSubTopic()
                title_topic.setTitle(item["level"]+"："+item['title'])
                # 前置条件
                pre_topic = title_topic.addSubTopic()
                pre_topic.setTitle('前置条件')
                pres=[]
                try:
                    pres = item['pre'].split('\n')
                except Exception as e:
                    pres.append(item['pre'])
                for pre in pres:
                    pre_child_topic = pre_topic.addSubTopic()
                    pre_child_topic.setTitle(pre.strip())
                # 步骤
                step_topic = title_topic.addSubTopic()
                step_topic.setTitle('操作步骤')
                steps=[]
                try:
                    steps = item['step'].split('\n')
                except Exception as e:
                    steps.append(item['step'])
                for step in steps:
                    step_child_topic = step_topic.addSubTopic()
                    step_child_topic.setTitle(step.strip())
                # 预期结果
                result_topic = title_topic.addSubTopic()
                result_topic.setTitle('预期结果')
                results=[]
                try:
                    results = item['result'].split('\n')
                except Exception as e:
                    results.append(item['result'])
                for result in results:
                    result_child_topic = result_topic.addSubTopic()
                    result_child_topic.setTitle(result.strip())
                # 备注
                remark_topic = title_topic.addSubTopic()
                remark_topic.setTitle('备注')
                remark_child_topic = remark_topic.addSubTopic()
                remark_child_topic.setTitle("AI生成")

        try:
            xmind.save(workbook, output_file)
            print(f'XMind file saved as {output_file}')
            return self.base_name
        except Exception as e:
            logger.error(f"数据验证过程中发生未知错误: {str(e)}")
            return '生成xmind失败'

    # os.startfile(output_file)
# Example usage
if __name__ == '__main__':
    sample_json = [
        {"testpoint": "测试点", "title": "用例标题", "pre": "前置条件", "step": "步骤描述", "level": "优先级", "remark": "备注"},
        {"testpoint": "测试点1", "title": "用例标题1", "pre": "1、xxx\n2、xxx", "step": "1、xxx\n2、xxx","result":"预期结果1", "level": "P0", "remark": "AI"},
        {"testpoint": "测试点1", "title": "用例标题2", "pre": "1、xxx\n2、xxx", "step": "1、xxx\n2、xxx","result":"预期结果1", "level": "P0", "remark": "AI"},
        {"testpoint": "测试点2", "title": "用例标题1", "pre": "1、xxx\n2、xxx","step": "1、xxx\n2、xxx","result":"预期结果1", "level": "P0", "remark": "AI"},
        {"testpoint": "测试点3", "title": "用例标题1", "pre": "1、xxx\n2、xxx", "step": "1、xxx\n2、xxx","result":"预期结果1", "level": "P1", "remark": "AI"},
        {"testpoint": "测试点1", "title": "用例标题1", "pre": "1、xxx\n2、xxx","step": "1、xxx\n2、xxx","result":"预期结果1", "level": "P1", "remark": "AI"}

    ]
    jsontoxmind=JsonToXmind(new_root='demon',json_data=sample_json,timestamp=datetime.now())
    jsontoxmind.json_to_xmind()